const config = require('./config')

export const upload = (filePath, data = {}) => {
	return new Promise((res, rej) => {
		uni.uploadFile({
			url: config.url + 'api/upload/image',
			filePath,
			header: {
				"Authorization": 'Bearer ' + uni.getStorageSync('token'),
				'userType': 'user'
			},
			name: 'file',
			formData: data,
			success: (uploadFileRes) => {
				console.log(uploadFileRes, '上传成功')
				res(JSON.parse(uploadFileRes.data))
			},
			fail: (res) => {
				console.log(res, '上传失败')
				rej(res)
			}
		})
	})
}

const MAXSIZE = 5
export const uploadImg = () => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			success: (res) => {
				const tempFilePaths = res.tempFilePaths;
				uni.getFileInfo({
					filePath: tempFilePaths[0],
					success: (info) => {
						
						const maxSize = MAXSIZE * 1024 * 1024; // 最大允许图片大小：5MB
						if (info.size > maxSize) {
							let title = '图片大小不能超过' + MAXSIZE + 'MB'
							uni.showToast({
								title,
								icon: 'none'
							})
							reject({
								msg: title,
								data: ''
							})
						} else {
							// this.uploadImage(tempFilePaths[0]);
							upload(tempFilePaths[0]).then(res => {
								
								resolve({
									msg: '',
									data: res.data
								})
							}).catch(err => {
								console.log('上传失败err=>', err)
								uni.showToast({
									title: '上传失败！',
									icon: 'none'
								})
								reject({
									msg: err,
									data: err
								})
							})
						}
					}
				});
			},
			fail: (err) => {
				console.error('选择图片失败', err);
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				})
				reject({
					msg: '选择图片失败',
					data: err
				})
			}
		});
	})
}
